package org.wzl.service.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.wzl.service.utils.Resp;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Resp<String> handleException(Exception e) {
        if (e.getCause() instanceof BusinessException) {
            return businessException((BusinessException)e.getCause());
        }
        log.error(e.getMessage(), e);
        return Resp.fail("系统错误");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public Resp<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
        String parameterName = ex.getParameterName();
        String message = "Required request parameter '" + parameterName + "' is missing";
        return Resp.fail(message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Resp<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        return Resp.fail(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }

    @ExceptionHandler(IllegalStateException.class)
    @ResponseBody
    public Resp<String> handleIllegalStateException(IllegalStateException ex) {
        return Resp.fail("参数不全");
    }

    @ExceptionHandler(BadCredentialsException.class)
    @ResponseBody
    public Resp<String> handleBadCredentialsException(BadCredentialsException ex) {
        return Resp.fail(ex.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Resp<String> businessException(BusinessException ex) {
        return Resp.fail(ex.getMessage());
    }


}
